import { getCurrentUser } from "@/api/api";

interface CheckcondictionProps {
  format?: string[];
  size?: number;
}
type ErrorType = "size" | "format" | null;
// type CheckFunc = () => object

// 上传图片验证
export function beforeUploadCheck(
  file: File,
  condiction: CheckcondictionProps
) {
  const isValidateType = condiction.format
    ? condiction.format.includes(file.type)
    : true;
  const isValidateSize = condiction.size
    ? file.size / 1024 / 1024 <= condiction.size
    : true;
  let error: ErrorType = null;
  if (!isValidateType) {
    error = "format";
  }
  if (!isValidateSize) {
    error = "size";
  }
  return {
    passd: isValidateSize && isValidateType,
    error,
  };
}

// 停止事件冒泡和默认行为
export function stopBubble(e: Event) {
  e.stopPropagation();
  console.log("stopBubble", e);
  return false;
}

// 获得css样式
export function getCss(curEle, attr: string) {
  return window.getComputedStyle
    ? window.getComputedStyle(curEle)[attr]
    : curEle.currentstyle[attr];
}

// 将一个对象属性值赋值给另一个对象属性
export function assignAttrToObj<T extends Record<string, any>, U extends T>(
  target: T,
  source: U,
  attrMap?: Map<keyof T, keyof U>
) {
  const keys = Object.keys(target);
  for (const k of keys as (keyof T)[]) {
    if (attrMap?.has(k)) {
      const key = attrMap.get(k);
      source[key as keyof U] && (target[k] = source[key as keyof U] as any);
    } else {
      source[k] && (target[k] = source[k]);
    }
  }
}

function joinArr(arr: any[], cutoff: string[] | string): string {
  if (typeof cutoff === "string") {
    return arr.join(cutoff);
  }
  const divide = " ";
  const ans = arr.reduce((pre, cur, curIndex, arr) => {
    return pre + cur + (cutoff[curIndex] ? cutoff[curIndex] : divide);
  }, "");
  return ans;
}
// 格式 yyyy-mm-dd hh:mm:ss split['-', ' ', ':']
// 格式 年月日
// 格式化时间
function doubleNum(n: number): string {
  return n >= 10 ? String(n) : "0" + n;
}
export function formatTime(
  time: string | Date,
  splitters?: (string | string[])[]
) {
  const t = new Date(time);
  const preSplitter = splitters ? splitters[0] : "-";
  const midSplitter = splitters ? splitters[1] : " ";
  const lastSplitter = splitters ? splitters[2] : ":";
  const preAns = joinArr(
    [t.getFullYear(), t.getMonth() + 1, t.getDate()].map(doubleNum),
    preSplitter
  );
  const lastAns = joinArr(
    [t.getHours(), t.getMinutes(), t.getSeconds()].map(doubleNum),
    lastSplitter
  );
  return `${preAns}${midSplitter}${lastAns}`;
}

export function checkAuth(id: string) {
  return getCurrentUser().then(
    (res) => {
      const { column } = res;
      console.log("column", column, "id", id);
      return column === id;
    },
    (err) => {
      return false;
    }
  );
  // return columnId === id
}
